package com.dfl.ggbond.pic;

import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.dfl.ggbond.R;
import com.dfl.ggbond.media.MediaInfo;
import com.dfl.ggbond.media.MediaLoad;
import com.dfl.ggbond.pic.adpter.PictureAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;

public class PictureActivity extends AppCompatActivity {

    private final List<MediaInfo> mediaList = new ArrayList<>();
    private RecyclerView recyclerView;
    private PictureAdapter adapter;
    private boolean isGrid = false; // 默认网格显示
    private Toolbar toolbar;
    private final Handler mainHandler = new Handler(Looper.getMainLooper());

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_picture);

        toolbar = findViewById(R.id.picture_toolbar);
        if (toolbar != null) {
            setSupportActionBar(toolbar);
            if (getSupportActionBar() != null) {
                getSupportActionBar().setDisplayShowTitleEnabled(true);
                getSupportActionBar().setTitle("Picture");
                getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            }
            toolbar.setNavigationOnClickListener(v -> finish());
        }

        recyclerView = findViewById(R.id.picture_recyclerview);
        initRecyclerView();

        // 权限检查
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {
            if (checkSelfPermission(android.Manifest.permission.READ_MEDIA_IMAGES) == PackageManager.PERMISSION_GRANTED) {
                loadImagesAndRefresh();
            } else {
                requestPermissions(new String[]{android.Manifest.permission.READ_MEDIA_IMAGES}, 100);
            }
        } else {
            if (checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                loadImagesAndRefresh();
            } else {
                requestPermissions(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, 100);
            }
        }
    }

    private void initRecyclerView() {
        if (recyclerView == null) return;
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager lm = isGrid ? new GridLayoutManager(this, 3) : new LinearLayoutManager(this);
        recyclerView.setLayoutManager(lm);

        adapter = new PictureAdapter(this, mediaList, isGrid);
        adapter.onItemClick = v -> {
            String uriStr = (String) v.getTag();
            if (uriStr != null) {
                try {
                    Intent i = new Intent(Intent.ACTION_VIEW);
                    i.setDataAndType(Uri.parse(uriStr), "image/*");
                    startActivity(i);
                } catch (Exception e) {
                    android.widget.Toast.makeText(this, "无法打开图片", android.widget.Toast.LENGTH_SHORT).show();
                }
            }
        };
        recyclerView.setAdapter(adapter);
    }

    private void setGridMode(boolean grid) {
        if (this.isGrid == grid) return;
        this.isGrid = grid;
        if (recyclerView != null) {
            if (isGrid) {
                recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
            } else {
                recyclerView.setLayoutManager(new LinearLayoutManager(this));
            }
        }
        if (adapter != null) adapter.setDisplayMode(isGrid);
    }

    // 后台读取图片并在主线程刷新 UI（返回 MediaInfo 列表）
    private void loadImagesAndRefresh() {
        MediaLoad.asyncLoadPicture(this, 0, Integer.MAX_VALUE, new MediaLoad.MediaDataCallback() {
            @Override
            public void onLoadComplete(List<MediaInfo> list) {
                mainHandler.post(()->{
                   mediaList.clear();
                   mediaList.addAll(list);
                   if(adapter != null) adapter.setData(mediaList);
                });
            }

            @Override
            public void onLoadError(Exception e) {
                mainHandler.post(()-> Toast.makeText(PictureActivity.this,"加载图片失败",Toast.LENGTH_SHORT).show());
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.picture_menu, menu);
        return true;
    }

    //右上角菜单点击事件
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        } else if (item.getItemId() == R.id.menu_grid) {
            setGridMode(true);
            return true;
        } else if (item.getItemId() == R.id.menu_list) {
            setGridMode(false);
            return true;
        } else if (item.getItemId() == R.id.menu_refresh) {
            loadImagesAndRefresh();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 100 && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            loadImagesAndRefresh();
        } else {
            android.widget.Toast.makeText(this, "权限不足，无法访问相册", android.widget.Toast.LENGTH_SHORT).show();
        }
    }

    // 查询 MediaStore 并构建 MediaInfo 列表
    private List<MediaInfo> queryImages() {
        List<MediaInfo> result = new ArrayList<>();
        Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

        String[] projection;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
            projection = new String[]{
                    MediaStore.Images.Media._ID,
                    MediaStore.Images.Media.DISPLAY_NAME,
                    MediaStore.Images.Media.SIZE,
                    MediaStore.Images.Media.DATE_ADDED,
                    MediaStore.Images.Media.DATE_MODIFIED,
                    MediaStore.Images.Media.MIME_TYPE,
                    MediaStore.Images.Media.WIDTH,
                    MediaStore.Images.Media.HEIGHT
            };
        } else {
            projection = new String[]{
                    MediaStore.Images.Media._ID,
                    MediaStore.Images.Media.DISPLAY_NAME,
                    MediaStore.Images.Media.DATA,
                    MediaStore.Images.Media.SIZE,
                    MediaStore.Images.Media.DATE_ADDED,
                    MediaStore.Images.Media.DATE_MODIFIED,
                    MediaStore.Images.Media.MIME_TYPE
            };
        }

        try (android.database.Cursor cursor = getContentResolver().query(uri, projection, null, null, MediaStore.Images.Media.DATE_ADDED + " DESC")) {
            if (cursor == null) return result;
            while (cursor.moveToNext()) {
                try {
                    long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
                    String name = "";
                    String path = "";
                    long size = 0L;
                    long dateAdded = 0L;
                    long dateModified = 0L;
                    String mime = "";
                    Integer width = null;
                    Integer height = null;

                    int idxName = cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME);
                    if (idxName != -1) name = cursor.getString(idxName);

                    int idxSize = cursor.getColumnIndex(MediaStore.Images.Media.SIZE);
                    if (idxSize != -1) size = cursor.isNull(idxSize) ? 0L : cursor.getLong(idxSize);

                    int idxAdded = cursor.getColumnIndex(MediaStore.Images.Media.DATE_ADDED);
                    if (idxAdded != -1)
                        dateAdded = cursor.isNull(idxAdded) ? 0L : cursor.getLong(idxAdded);

                    int idxModified = cursor.getColumnIndex(MediaStore.Images.Media.DATE_MODIFIED);
                    if (idxModified != -1)
                        dateModified = cursor.isNull(idxModified) ? 0L : cursor.getLong(idxModified);

                    int idxMime = cursor.getColumnIndex(MediaStore.Images.Media.MIME_TYPE);
                    if (idxMime != -1) mime = cursor.getString(idxMime);

                    int idxWidth = cursor.getColumnIndex("width");
                    if (idxWidth != -1)
                        width = cursor.isNull(idxWidth) ? null : cursor.getInt(idxWidth);
                    int idxHeight = cursor.getColumnIndex("height");
                    if (idxHeight != -1)
                        height = cursor.isNull(idxHeight) ? null : cursor.getInt(idxHeight);

                    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.Q) {
                        int idxData = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
                        if (idxData != -1) path = cursor.getString(idxData);
                    } else {
                        // 对于 Q 及以上，用 content Uri 作为 path 字段的可读表示
                        path = ContentUris.withAppendedId(uri, id).toString();
                    }

                    Uri contentUri = ContentUris.withAppendedId(uri, id);

                    MediaInfo info = new MediaInfo(
                            id,
                            name != null ? name : "",
                            path != null ? path : "",
                            contentUri,
                            size,
                            dateAdded,
                            dateModified,
                            mime != null ? mime : "",
                            width,
                            height,
                            null,
                            null,
                            null
                    );
                    result.add(info);
                } catch (Exception ignored) {
                }
            }
        } catch (Exception ignored) {
        }
        return result;
    }
}